<template>
  <view class="wrapper">
    <view class="tabsBox">
      <u-tabs
        :list="tabsList"
        lineWidth="50rpx"
        lineColor="#FF4400"
        :activeStyle="{
          color: '#333333',
          fontWeight: 'bold',
          fontSize: '30rpx',
        }"
        :inactiveStyle="{
          color: '#666666',
          fontWeight: 'bold',
          fontSize: '30rpx',
        }"
        :current="current"
        @click="tabsClick"
      ></u-tabs>
    </view>
    <!-- <u-refresh-complete ref="uRefreshComplete"/> -->
    <view class="main">
      <view v-if="current === 0">
        <view class="goods">
          <template v-if="!loading && goodsList.length === 0">
            <view class="goods-empty">
              <u-empty mode="data" text="暂无商品"></u-empty>
            </view>
          </template>
          <template v-else>
            <view
              class="goods-item"
              v-for="(item, index) in goodsList"
              :key="index"
            >
              <image
                class="goods-item-img"
                :src="item.product_image"
                mode="aspectFill"
              ></image>
              <view class="goods-item-name">
                {{ item.product_name }}
              </view>
              <view class="goods-item-btn" @click="orderNow(item)">
                立即进货
                <u-icon name="arrow-right" color="#fff" size="38rpx"></u-icon>
              </view>
            </view>
          </template>
        </view>
        <!-- 加载更多 -->
        <u-loadmore
          :status="loadStatus"
          :loading-text="loadingText"
          :loadmore-text="loadmoreText"
          :nomore-text="nomoreText"
          v-if="goodsList.length > 0"
        />
      </view>
      <view class="inventory" v-if="current === 1">
        <template v-if="!inventoryLoading && inventoryList.length === 0">
          <view class="inventory-empty">
            <u-empty mode="data" text="暂无库存商品"></u-empty>
          </view>
        </template>
        <template v-else>
          <view
            class="inventory-item"
            v-for="(item, index) in inventoryList"
            :key="item.id"
          >
            <view class="inventory-item-time">
              <view class="inventory-item-index">
                {{ index + 1 }}
              </view>
              创建时间: {{ item.create_time || "--" }}
            </view>
            <view class="inventory-item-name">
              {{ item.product_name || "--" }}
              <view class="inventory-item-label" v-if="item.is_insured"
                >已投保</view
              >
            </view>
            <view class="inventory-item-text"
              >规格: {{ item.spec_name || "--" }}</view
            >
            <view class="inventory-item-text"
              >期数: {{ item.lease_term || "--" }}期</view
            >
            <view class="inventory-item-text" style="margin-bottom: 0"
              >价格: ￥{{ item.price || "0.00" }}</view
            >
            <view class="inventory-item-box">
              <view class="inventory-item-box-status">
                {{ getStatusText(item.leasing_status) }}
              </view>
              <view class="inventory-item-box-day" v-if="item.lease_days">
                {{ item.lease_days }}
                <text>天</text>
              </view>
            </view>
            <view class="inventory-item-footer">
              <view class="inventory-item-footer-item btnOne" @click="handleWithdraw(item)">确认退还</view>
              <view class="inventory-item-footer-item btnTwo" @click="handleRecommission(item)">再次委托</view>
            </view>
          </view>
          <u-loadmore
            :status="loadStatus"
            :loading-text="loadingText"
            :loadmore-text="loadmoreText"
            :nomore-text="nomoreText"
            v-if="inventoryList.length > 0"
          />
        </template>
      </view>
    </view>
    <!-- 自定义弹窗组件 -->
    <custom-modal
      :show="showModal"
      :title="modalTitle"
      :buttons="{
        showCancel: true,
        showConfirm: true,
        confirmText: '确认',
        cancelText: '取消',
      }"
      :options="{
        closeOnClickOverlay: true,
        width: '490rpx',
      }"
      @confirm="handleConfirm"
      @cancel="handleCancel"
      @close="handleCancel"
    >
      <view class="modal-content">
        <view class="modal-line" v-html="modalContent"></view>
      </view>
    </custom-modal>
  </view>
</template>

<script>
import rental from '@/api/modules/rental'
import { product as productApi } from "@/api";
import { getInventoryList } from "@/api/modules/rental";
import customModal from "@/components/custom-modal.vue";
export default {
  components: {
    customModal,
  },
  onReachBottom() {
    if (this.current === 0) {
      if (this.loading || this.finished) return;
      this.loadStatus = "loading";
      this.page++;
      this.fetchProducts();
    } else {
      if (this.inventoryLoading || this.inventoryFinished) return;
      this.loadStatus = "loading";
      this.inventoryPage++;
      this.fetchInventoryList();
    }
  },
  data() {
    return {
      current: 0,
      tabsList: [
        {
          name: "商品进货",
        },
        {
          name: "我的库存",
        },
      ],
      // 商品列表相关
      goodsList: [],
      // 库存列表相关
      inventoryList: [],
      inventoryPage: 1,
      inventoryTotal: 0,
      inventoryLoading: false,
      inventoryFinished: false,
      // 分页相关
      page: 1,
      list_rows: 10,
      loading: false,
      loadStatus: "loadmore",
      loadingText: "正在加载...",
      loadmoreText: "上拉加载更多",
      nomoreText: "没有更多了",
      finished: false,
      // 弹窗相关
      showModal: false,
      modalTitle: '温馨提示',
      modalContent: '',
      modalType: '', // 'recommission' or 'withdraw'
      currentItem: null, // 当前操作的库存项
    };
  },
  onLoad() {
    this.fetchProducts();
  },
  async onPullDownRefresh() {
    if (this.current === 0) {
      this.page = 1;
      this.finished = false;
      this.loadStatus = "loadmore";
      await this.fetchProducts();
      uni.stopPullDownRefresh();
    } else {
      this.inventoryPage = 1;
      this.inventoryFinished = false;
      this.loadStatus = "loadmore";
      await this.fetchInventoryList();
      uni.stopPullDownRefresh();
    }

    if (this.refreshing) {
      uni.stopPullDownRefresh();
      this.refreshing = false;
    }
  },
  watch: {
    current(newVal) {
      if (newVal === 1 && this.inventoryList.length === 0) {
        this.fetchInventoryList();
      }
    },
  },
  methods: {
    orderNow(item) {
      uni.navigateTo({
        url: `/package-purse/orderNow/orderNow?id=${item.product_id}`,
      });
    },
    tabsClick(item) {
      this.current = item.index;
    },
    // 获取库存列表
    async fetchInventoryList() {
      if (this.inventoryLoading) return;

      this.inventoryLoading = true;
      this.loadStatus = "loading";

      try {
        const params = {
          page: this.inventoryPage,
          list_rows: this.list_rows,
          leasing_status: "0", // 默认查询在库商品
        };

        const { data } = await getInventoryList(params);
        const items = data?.data || [];

        if (this.inventoryPage === 1) {
          this.inventoryList = items;
        } else {
          this.inventoryList = [...this.inventoryList, ...items];
        }

        this.inventoryTotal = data.total || 0;

        // 判断是否还有更多数据
        if (
          items.length < this.list_rows ||
          this.inventoryList.length >= this.inventoryTotal
        ) {
          this.inventoryFinished = true;
          this.loadStatus = "nomore";
        } else {
          this.loadStatus = "loadmore";
        }
      } catch (error) {
        console.error("获取库存列表失败:", error);
        uni.showToast({
          title: "获取库存列表失败",
          icon: "none",
        });
        this.loadStatus = "loadmore";
        uni.stopPullDownRefresh();
      } finally {
        this.inventoryLoading = false;
      }
    },
    async fetchProducts() {
      if (this.loading) return;

      this.loading = true;
      if (this.page === 1) {
        this.goodsList = [];
      }

      try {
        const params = {
          page: this.page,
          list_rows: this.list_rows,
          app_id: this.getAppId && this.getAppId() ? this.getAppId() : 10001,
        };

        const { data } = await productApi.getProductList(params);
        const newItems = Array.isArray(data?.data) ? data?.data : [];

        if (this.page === 1) {
          this.goodsList = newItems;
        } else {
          this.goodsList = [...this.goodsList, ...newItems];
        }

        this.total = data.total || 0;

        // 判断是否还有更多数据
        if (
          newItems.length < this.list_rows ||
          this.goodsList.length >= this.total
        ) {
          this.finished = true;
          this.loadStatus = "nomore";
        } else {
          this.loadStatus = "loadmore";
        }
      } catch (e) {
        console.error("获取商品列表失败", e);
        this.loadStatus = "loadmore";
        uni.showToast({
          title: "获取商品列表失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },
    getStatusText(status) {
      const statusMap = {
        0: "待出租",
        1: "匹配中",
        2: "出租中",
        3: "已退机",
        4: "半路退机",
        5: "已完结",
      };
      return statusMap[status] || "--";
    },
    // 处理再次委托
    handleRecommission(item) {
      this.currentItem = item;
      this.modalType = 'recommission';
      this.modalTitle = '温馨提示';
      this.modalContent = '再次委托出租机率较高，确定再次委托吗？';
      this.showModal = true;
    },
    // 处理立即退机
    handleWithdraw(item) {
      this.currentItem = item;
      this.modalType = 'withdraw';
      this.modalTitle = '温馨提示';
      this.modalContent = '确认退还后，本金将会退还到余额里面。';
      this.showModal = true;
    },
    // 处理确认操作
    async handleConfirm() {
      // 保存当前操作类型，避免在finally中被清除
      const currentAction = this.modalType;
      try {
        if (this.modalType === 'recommission') {
          // 执行再次委托的逻辑
          await rental.reEntrustLeasing(this.currentItem.id);
          uni.showToast({
            title: '已提交再次委托申请',
            icon: 'success'
          });
          // 刷新列表
          this.inventoryPage = 1;
          this.inventoryList = [];
          await this.fetchInventoryList();
        } else if (this.modalType === 'withdraw') {
          // 执行退机的逻辑
          await rental.returnDevice(this.currentItem.id);
          uni.showToast({
            title: '退机申请已提交',
            icon: 'success'
          });
          // 刷新列表
          this.inventoryPage = 1;
          this.inventoryList = [];
          await this.fetchInventoryList();
        }
      } catch (error) {
        const errorMessage = currentAction === 'recommission' ? '再次委托' : '退机';
        console.error(`${errorMessage}失败:`, error);
        uni.showToast({
          title: `${errorMessage}失败`,
          icon: 'none'
        });
      } finally {
        this.showModal = false;
        this.currentItem = null;
        this.modalType = '';
      }
    },
    // 处理取消操作
    handleCancel() {
      this.showModal = false;
      this.currentItem = null;
      this.modalType = '';
    },
  },
};
</script>

<style lang="scss" scoped>
.wrapper {
  padding: 0 30rpx 30rpx;
}

.tabsBox {
  padding: 10rpx 70rpx 0 70rpx;

  ::v-deep .u-tabs__wrapper__nav__item {
    width: 50%;
    box-sizing: border-box;
  }
}

.main {
  padding: 20rpx 0rpx;
}

.goods {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  justify-content: space-between;
  &-empty {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60vh;
  }
  &-item {
    width: 47.5%;
    margin-bottom: 30rpx;
    background: #ffffff;
    border-radius: 10rpx;

    &-img {
      margin: 0 auto;
      width: 330rpx;
      height: 330rpx;
      border-radius: 10rpx 10rpx 0 0;
    }

    &-name {
      margin: 30rpx 0;
      text-align: center;
      font-family: "PingFang SC";
      font-weight: bold;
      font-size: 28rpx;
      color: #333333;
    }

    &-btn {
      font-family: "PingFang SC";
      font-weight: bold;
      font-size: 36rpx;
      color: #ffffff;
      height: 89rpx;
      background: #ff4400;
      border-radius: 0 0 10rpx 10rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

.inventory {
  &-empty {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60vh;
  }
  &-item {
    position: relative;
    padding: 30rpx 0;
    background: #ffffff;
    border-radius: 14rpx;
    margin-bottom: 20rpx;
    font-family: "PingFang SC";
    font-weight: 400;
    font-size: 24rpx;
    color: #999999;

    &-time {
      display: flex;
      align-items: center;
    }

    &-index {
      width: 67rpx;
      height: 32rpx;
      background: rgba(255, 68, 0, 0.1);
      border-radius: 0 6rpx 6rpx 0;
      line-height: 32rpx;
      text-align: center;
      font-family: "PingFang SC";
      font-weight: 500;
      font-size: 26rpx;
      color: #ff0000;
      margin-right: 20rpx;
    }

    &-name {
      display: flex;
      align-items: center;
      padding-left: 30rpx;
      font-family: "PingFang SC";
      font-weight: 500;
      font-size: 30rpx;
      color: #333333;
      margin: 30rpx 0;
    }

    &-text {
      margin-bottom: 30rpx;
      padding-left: 30rpx;
      font-family: "PingFang SC";
      font-weight: 400;
      font-size: 24rpx;
      color: #999999;
    }

    &-label {
      margin-left: 10rpx;
      padding: 2rpx;
      background: rgba(255, 109, 56, 0.8);
      border-radius: 4rpx;
      font-family: "PingFang SC";
      font-weight: 400;
      font-size: 22rpx;
      color: #ffffff;
    }

    &-box {
      position: absolute;
      top: 30rpx;
      right: 55rpx;

      &-status {
        font-family: "PingFang SC";
        font-weight: 400;
        font-size: 24rpx;
        color: #999999;
      }

      &-day {
        margin-top: 30rpx;
        display: flex;
        align-items: center;
        font-family: PingFang SC;
        font-weight: 500;
        font-size: 36rpx;
        color: #333333;

        text {
          margin-left: 5rpx;
          font-weight: 400;
          font-size: 24rpx;
          color: #333333;
        }
      }
    }

    &-footer {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      margin-top: 14rpx;
      padding-right: 20rpx;

      &-item {
        width: 140rpx;
        height: 50rpx;
        border-radius: 6rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .btnOne {
        background: rgba(255, 68, 0, 0.1);
        font-family: "PingFang SC";
        font-weight: 500;
        font-size: 24rpx;
        color: #ff4603;
      }

      .btnTwo {
        background: #ff4400;
        font-family: "PingFang SC";
        font-weight: 500;
        font-size: 24rpx;
        color: #ffffff;
        margin-left: 20rpx;
      }
    }
  }
}
.modal-content {
	padding: 44rpx 60rpx;
}
.modal-line {
	font-family: PingFang SC;
	font-weight: 400;
	font-size: 28rpx;
	color: #666666;
}
</style>
